<script setup>
  import { onClickOutside } from '@vueuse/core'

  import { useField } from 'vee-validate'
  import { inject, ref } from 'vue'
  import { formContextInjectionKey } from '@/helpers/form'
  import { findCity } from '@/helpers/apiGouv'
  import Input from '@/components/forms/Input.vue'

  const { handleChange: cityChange } = useField('city')
  const { value: cityCode, handleChange: cityCodeChange } =
    useField('city_code')
  const { getFormFieldData } = inject(formContextInjectionKey)

  const props = defineProps({
    completion: { type: Boolean, default: false },
  })
  // Stocke la liste des villes possibles
  let cityOptions = ref([])
  let currentQuery
  const onSelectCity = (index) => {
    const selectedCity = cityOptions.value[index]
    if (selectedCity) {
      cityChange(selectedCity.nom)
      cityCodeChange(selectedCity.code)
      cityOptions.value = []
    }
  }
  const completeCity = (searchObject) => {
    if (currentQuery) {
      clearTimeout(currentQuery)
    }
    currentQuery = setTimeout(async () => {
      cityOptions.value = await findCity(searchObject)
      if (cityOptions.value.length === 1) {
        onSelectCity(0)
      }
    }, 300)
  }
  const onChangeCity = (value) => {
    if (props.completion) {
      if (value.length >= 3) {
        completeCity({ nom: value })
      }
    }
  }
  const onChangeZipCode = (value) => {
    if (props.completion) {
      completeCity({ codePostal: value })
    }
  }
  const dropdownTarget = ref(null)

  onClickOutside(dropdownTarget, (event) => {
    cityOptions.value = []
  })
</script>
<template>
  <div class="row form-row">
    <div class="col-md-4 form-group String">
      <Input
        v-bind="getFormFieldData('zip_code')"
        v-on:change-value="onChangeZipCode"
      />
    </div>
    <div class="col-md-8 form-group String">
      <Input
        v-bind="getFormFieldData('city')"
        v-on:change-value="onChangeCity"
      />

      <div v-if="cityOptions" class="form-autocomplete" ref="dropdownTarget">
        <ul>
          <li v-for="(option, index) in cityOptions">
            <a href="javascript:void(0);" @click="() => onSelectCity(index)">
              {{ option.nom }} ({{ option.codeDepartement }})
            </a>
          </li>
        </ul>
      </div>
      <input
        v-if="!completion"
        type="hidden"
        name="city_code"
        :value="cityCode"
      />
    </div>
  </div>
</template>
